package juc.utils.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * exchange的是同一个对象，不是拷贝
 */
public class ExchangeExample2 {
    public static void main(String[] args) {
        final Exchanger<Object> exchanger = new Exchanger<>();
        new Thread() {
            @Override
            public void run() {
                Object aObj = new Object();
                System.out.println("A will send the object." + aObj);
                try {
                    Object rObj = exchanger.exchange(aObj);
                    System.out.println("A received the object." + rObj);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                Object bObj = new Object();
                System.out.println("B will send the object." + bObj);
                try {
                    Object rObj = exchanger.exchange(bObj);
                    System.out.println("B received the object." + rObj);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
